package org.sshproxy;

import android.app.ActivityManager;
import android.os.Bundle;

import java.io.File;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;


import android.content.Context;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.AssetManager;

import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;

import android.util.Log;

public class sshproxy extends PreferenceActivity implements 
    OnSharedPreferenceChangeListener
{
    private EditTextPreference userText;
    private EditTextPreference hostText;
    private EditTextPreference passwdText;
    private EditTextPreference portText;
    private CheckBoxPreference srvCtl;

    private static final String TAG="SSHProxy";
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        addPreferencesFromResource(R.layout.ui);

        CopyAssets();

        userText =  (EditTextPreference) findPreference("user");
        hostText =  (EditTextPreference) findPreference("host");
        passwdText =  (EditTextPreference) findPreference("passwd");
        portText =  (EditTextPreference) findPreference("port");
        srvCtl = (CheckBoxPreference) findPreference("srv_ctl");
    }
    public void checkStatus(){
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        Process process = null;
        String cmd="pidof plink";
        try{
            process = Runtime.getRuntime().exec(cmd);
            process.waitFor();
        }catch (Exception e){
            Log.d(TAG,e.getMessage());
            //Log.d(TAG,e);
        }
        if (process.exitValue() != 0){
            Editor edit=settings.edit();
            edit.putBoolean("isRunning",false);
            edit.commit();
        }else
        disableAll();
    }

    public void enableAll(){
        hostText.setEnabled(true);
        userText.setEnabled(true);
        passwdText.setEnabled(true);
        portText.setEnabled(true);
    }
    public void disableAll(){
        hostText.setEnabled(false);
        userText.setEnabled(false);
        passwdText.setEnabled(false);
        portText.setEnabled(false);
    }
    public void onSharedPreferenceChanged(SharedPreferences sharedPreference,
            String key){
        
        //Log.d(TAG,"preference changed: " + key);
        final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);

        if(key.equals("srv_ctl")){
            String user=settings.getString("user","");
            String pw=settings.getString("passwd","");
            String host=settings.getString("host","");
            String port=settings.getString("port","");
            if (settings.getBoolean("srv_ctl",false)){
                //Log.d(TAG,"checkbox checked");
                Process process = null;
                String cmd="/data/data/org.sshproxy/proxy.sh start " + host + " " +
                    user + " " + pw + " " + port + " " + 1;
                try{
                process = Runtime.getRuntime().exec(cmd);
                }catch (Exception e){
                    Log.d(TAG,e.getMessage());
                }
                //process.waitFor();
                new Thread(){
                    public void run(){
                        try {
                        Thread.sleep(13000);
                        } catch(Exception e){
                            Log.d(TAG,e.getMessage());
                            //Log.d(TAG,e);
                        }
                        checkStatus();
                    }
                }.start();
                Editor edit=settings.edit();
                edit.putBoolean("isRunning",true);
                edit.commit();
            }
            else{
                //log.d(tag,"checkbox unchecked");
                Process process = null;
                String cmd="/data/data/org.sshproxy/proxy.sh stop - - - - 1";
                try{
                process = Runtime.getRuntime().exec(cmd);
                } catch (Exception e){
                    Log.d(TAG,e.getMessage());
                    //Log.d(TAG,e);
                }
                //process.waitfor();
            }
        }
        if (key.equals("isRunning")){
            if(!settings.getBoolean("isRunning",false)){
                srvCtl.setChecked(false);
                enableAll();
            }else{
                disableAll();
            }
        }
        if (key.equals("user")){
           if(settings.getString("user","").equals(""))
              userText.setSummary(getString(R.string.user_summary));
           else
              userText.setSummary(settings.getString("user","")); 
        }
        if (key.equals("port")){
           if(settings.getString("port","").equals(""))
              portText.setSummary(getString(R.string.port_summary));
           else
              portText.setSummary(settings.getString("port","")); 
        }
        if (key.equals("host")){
           if(settings.getString("host","").equals(""))
              hostText.setSummary(getString(R.string.host_summary));
           else
              hostText.setSummary(settings.getString("host","")); 
        }
        if (key.equals("passwd")){
           if(settings.getString("passwd","").equals(""))
              passwdText.setSummary(getString(R.string.passwd_summary));
           else
              passwdText.setSummary("*********");
        }
       
        
    }

    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferencescreen,
            Preference preference){

        return super.onPreferenceTreeClick(preferencescreen, preference);
    }

    public void CopyAssets(){
        AssetManager  assetManager = getAssets();
        String[] files = null;
        String baseDir = "/data/data/org.sshproxy/";
        try {
            files = assetManager.list("");
        } catch (IOException e){
            Log.e(TAG,e.getMessage());
        }
        for (int i = 0; i < files.length; i++){
            InputStream in = null;
            OutputStream out = null;
            try {
                String fileName = baseDir + files[i];
                if (!isFileExists(fileName)){
                    in = assetManager.open(files[i]);
                    out = new FileOutputStream(fileName);
                    copyFile(in, out);
                    in.close();
                    in = null;
                    out.flush();
                    out.close();
                    out = null;
                    try{
                    Process p=Runtime.getRuntime().exec("chmod 755 " + fileName);
                    p.waitFor();
                    }catch (Exception e){
                        Log.d(TAG,e.getMessage());
                    }
                }
            } catch (Exception e){
                Log.e(TAG,e.getMessage());
            }
        }
    }

    public boolean isFileExists(String f){
        return new File(f).exists();
    }

    public void copyFile(InputStream in, OutputStream out){
        byte[] buffer  = new byte[1024];
        int size;
        try{
        while((size = in.read(buffer)) != -1){
            out.write(buffer,0, size);
        }
        }catch(Exception e){
            Log.d(TAG,e.getMessage());
            //Log.d(TAG,e);
        }
    }

    @Override
    protected void onResume () {
        super.onResume();
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        if (!settings.getString("user","").equals(""))
            userText.setSummary(settings.getString("user",
                        getString(R.string.user_summary)));
        if (!settings.getString("port","").equals(""))
            portText.setSummary(settings.getString("port",
                        getString(R.string.port_summary)));
        if (!settings.getString("host","").equals(""))
            hostText.setSummary(settings.getString("host",
                        getString(R.string.host_summary)));
        if (!settings.getString("passwd","").equals(""))
            passwdText.setSummary("*********");
        getPreferenceScreen().getSharedPreferences()
            .registerOnSharedPreferenceChangeListener(this);
        new Thread(){
            public void run(){
                checkStatus();
            }
        }.start();
    }

    @Override
    protected void onPause(){
        super.onPause();
        getPreferenceScreen().getSharedPreferences()
            .unregisterOnSharedPreferenceChangeListener(this);
    }

}
